import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app/bean/file_path_entity.dart';
import 'package:flutter_app/bean/list_jx_org_by_pid_entity.dart';
import 'package:flutter_app/bean/problem_by_code_entity.dart';
import 'package:flutter_app/manager/AppSetInfoManager.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/network/UploadFilesUtils.dart';
import 'package:flutter_app/ui/collect/query_list2/query_list_logic.dart';
import 'package:flutter_app/ui/main/main_logic.dart';
import 'package:flutter_app/utils/DialogUtils.dart';
import 'package:flutter_app/utils/EventBusUtils.dart';
import 'package:flutter_app/utils/device_info_utils.dart';
import 'package:flutter_app/utils/logger_utils.dart';
import 'package:flutter_app/utils/prevent_tap_utils.dart';
import 'package:flutter_app/utils/sp_utils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:flutter_app/values/CommonParam.dart';
import 'package:get/get_navigation/get_navigation.dart';
import 'package:get/instance_manager.dart';
import 'package:get/state_manager.dart';
import 'package:image_pickers/image_pickers.dart';

import 'query_detail_state.dart';

class QueryDetailLogic extends GetxController {
  final QueryDetailState state = QueryDetailState();

  final mainLogic = Get.find<MainLogic>();
  final queryLogic = Get.find<QueryListLogic>();


  late TextEditingController textCtrl;
  late TextEditingController textRemark;

  late String groupId;
  late String orgId;
  late String problemCode;

  // 要上传的文件
  List<Media> imagesList = [];
  // 当前问题 填报的文件list
  List<FilePathEntity> filePathList = [];
  // 编辑框 二级部门 输入的内容
  String editRemarkStr = "";
  // 编辑框 详细说明 输入的内容
  String editContentStr = "";

  @override
  void onInit() {
    super.onInit();
    textCtrl = TextEditingController();
    textRemark = TextEditingController();

    groupId = queryLogic.groupId;
    orgId = queryLogic.orgId;
    problemCode = Get.arguments["problemCode"];
    state.typeName = Get.arguments["typeName"];
    state.taskStatus = queryLogic.memberStatus == "0";
  }

  @override
  void onReady() {
    super.onReady();
    checkAuthDevice();
    listProblemByCode();
    // listJxOrgByPid();
  }

  /// 获取厅局下所有科室（下级机构查询 非分厅）
  Future<void> listJxOrgByPid() async {
    Map<String, dynamic> param = {
      "oneParam": orgId,
      // "oneParam": "02.01.0000.0002.0003",
    };
    ResultData resultData = await Api.listJxOrgByPid(param);
    if (resultData.isSuccess) {
      List<dynamic> list = jsonDecode(jsonEncode(resultData.data['data']));
      state.listJxOrgByPidEntity = list.map((e) => ListJxOrgByPidEntity.fromJson(e)).toList();
      state.listJxOrgByPidEntity?.forEach((element) { 
        state.listOrg.add(element.orgName ?? "");
      });
      update();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  /// 根据问题清单获取上报问题列表
  Future<void> listProblemByCode() async {
    Map<String, dynamic> param = {
      "groupId": groupId,
      "orgId": orgId,
      "problemCode": problemCode,
    };
    ResultData resultData = await Api.listProblemByCode(param);
    if (resultData.isSuccess) {
      List<dynamic> list = jsonDecode(jsonEncode(resultData.data['data']));
      state.problemByCodeEntity = list.map((e) => ProblemByCodeEntity.fromJson(e)).toList();
      update();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  /// 获取清单和关联上报问题列表
  Future<void> checkAuthDevice() async {
    // App配置 全局开启 不验证
    if (AppSetInfoManager().getPinState() == "1") {
      return;
    }
    // 设备没有开启权限 不验证
    if (mainLogic.state.pinPutState.value == false) {
      return;
    }

    Map<String, dynamic> param = {
      "id": await DeviceInfoUtils().getDeviceId,
    };
    ResultData resultData = await Api.checkAuthDevice(param);
    if (resultData.isSuccess) {
      String data = resultData.data["data"];
      // 0无授权记录1已授权2授权已解除
      if (data != "1") {
        mainLogic.state.pinPutState.value = false;
        await sp.setBool(CommonParam.PIN_PUT_STATE, false);
        if (data == "2") {
          toast.show(resultData.data["本地相册权限已被解除，请联系管理员"]);
        }
      }
    }
  }

  // 点击保存按钮
  Future<void> save({int? index}) async {
    if (PreventTapUtils().multiTouch()) {
      return;
    }

    if (textCtrl.text.isEmpty) {
      toast.show("请信填写违规内容。");
      return ;
    }

    List<FilePathEntity> filePathEntity;

    // 有网络文件的时候 ：文件已经上传，重新进行编辑
    if (index != null) {
      if (state.problemByCodeEntity![index].fileList?.length == 0) {
        if (state.problemByCodeEntity![index].imagesList == null) {
          toast.show("请选择图片、视频证据!");
          return;
        } else {
          if (state.problemByCodeEntity![index].imagesList?.length == 0) {
            toast.show("请选择图片、视频证据!");
            return;
          }
        }
      }
      if ((state.problemByCodeEntity![index].imagesList?.length ?? 0) > 0) {
        filePathEntity = await UploadFilesUtils().upload(state.problemByCodeEntity![index].imagesList!);
        if ((state.problemByCodeEntity![index].imagesList?.length ?? 0) != filePathEntity.length) {
          dialogUtils.show(
            context: Get.context!,
            title: "提示",
            content: "文件未全部上传，重新尝试？",
            callbackOk: () {
              save(index: index);
            },
          );
          return;
        }
        state.problemByCodeEntity![index].fileList?.addAll(filePathEntity);
      }
      postSaveProblemSubmit(state.problemByCodeEntity![index].toJson(), index: index);
    } else {
    // 无网络文件的时候：一个新的事项进行添加
      if (imagesList.length == 0 ) {
        toast.show("请选择图片、视频证据!");
        return;
      }
      filePathEntity = await UploadFilesUtils().upload(imagesList);
      if (imagesList.length != filePathEntity.length) {
        dialogUtils.show(
          context: Get.context!,
          title: "提示",
          content: "文件未全部上传，重新尝试？",
          callbackOk: () {
            save();
          },
        );
        return;
      }
      ProblemByCodeEntity problemByCodeEntity = new ProblemByCodeEntity();
      problemByCodeEntity.groupId = groupId;
      problemByCodeEntity.orgId = orgId;
      problemByCodeEntity.problemCode = problemCode;
      problemByCodeEntity.content = editContentStr;
      problemByCodeEntity.fileList = filePathEntity;
      problemByCodeEntity.remark = editRemarkStr;
      postSaveProblemSubmit(problemByCodeEntity.toJson());
    }
    Get.back();
  }

  /// 保存问题填报信息
  Future<void> postSaveProblemSubmit(Map<String, dynamic> param, {int? index}) async {

    ResultData resultData = await Api.postSaveProblemSubmit(param);

    if (resultData.isSuccess) {
      if (index == null) {
        // 置空 弹窗上的数据
        imagesList.clear();
        editContentStr = "";
        editRemarkStr = "";
      }
      bus.fire(CollectAddNum());
      listProblemByCode();
    }
    toast.show(resultData.data["message"]);
  }

  /// 删除问题填报接口
  Future<void> postDeleteProblem(int index) async {
    if (!state.taskStatus) {
      return toast.show("问题已确认，不可删除");
    }
    if (state.problemByCodeEntity![index].isSelf != "1") {
      return toast.show("非本人上传，不可操作");
    }

    Map<String, dynamic> param = {
      "id": state.problemByCodeEntity![index].id,
    };
    ResultData resultData = await Api.postDeleteProblem(param);
    if (resultData.isSuccess) {
      state.problemByCodeEntity?.removeAt(index);
      update();
    }
    toast.show(resultData.data["message"]);
  }

  /// 判断是否有编辑权限
  bool editState({int? index}) {
    // taskStatus 任务状态
    // 是不是自己上传的数据 isSelf 0否1是
    if (index != null && state.taskStatus) {
      return state.problemByCodeEntity![index].isSelf == "1";
    } else {
      return state.taskStatus;
    }
  }

  bool dialogEditState = false; // 是否要清空输入框重新赋值

  String tsStr = ""; // 暂存的输入框数据
  List<Media> tsImagesList = []; // 暂存的媒体文件

  /// 判断是否要给弹窗 重新赋值
  void reassign({int? index}) {
    if (index != null) {
       textCtrl.text = state.problemByCodeEntity![index].content ?? "";
       textRemark.text = state.problemByCodeEntity![index].remark ?? "";
    } else {
      textCtrl.text = editContentStr;
      textRemark.text = editRemarkStr;
    }
  }

  @override
  void onClose() {
    super.onClose();
  }

}
